package com.jiulan.hearthearing.ui.heart.fragment;

import android.content.Context;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.jiulan.hearthearing.R;
import com.jiulan.hearthearing.base.BaseVPFragment;
import com.jiulan.hearthearing.constants.Constants;
import com.jiulan.hearthearing.constants.UrlConstants;
import com.jiulan.hearthearing.http.HttpRequest;
import com.jiulan.hearthearing.http.HttpStringCallBack;
import com.jiulan.hearthearing.ui.heart.adapter.ClassifyAdapter;
import com.jiulan.hearthearing.ui.heart.adapter.ClassifyFlowAdapter;
import com.jiulan.hearthearing.ui.heart.model.ClassifyModel;
import com.jiulan.hearthearing.ui.heart.model.CourseListModle;
import com.library.flowlayout.FlowLayoutManager;
import com.library.flowlayout.NestedRecyclerView;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnLoadMoreListener;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class CourseLiveFragment extends BaseVPFragment implements View.OnClickListener {
    private Context context;
    private int id = 0;
    private String child = "";
    private List<ClassifyModel.DataBean.ChildBean> childBeans;
    private ClassifyAdapter adapter;
    private int cid;
    private String keyword = "";
    private int page = 1;
    private int type = 1;
    private int count = 0;
    private List<CourseListModle.DataBean.ListBean> data;

    private NestedRecyclerView flowLayout;
    private SmartRefreshLayout smartLayout;
    private RecyclerView rcvCourse;
    private TextView tvCourseNum;
    private TextView tvOnLive;
    private TextView tvLive;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_classify_live, container, false);
        initView(view);
        return view;
    }

    private void initView(View view) {
        context = getActivity();
        Bundle arguments = getArguments();
        type = arguments.getInt("from");
        id = arguments.getInt("id");
        child = arguments.getString("child", "");
        flowLayout = view.findViewById(R.id.flowLayout);
        smartLayout = view.findViewById(R.id.smartLayout);
        rcvCourse = view.findViewById(R.id.rcvCourse);
        rcvCourse.setLayoutManager(new LinearLayoutManager(context));
        tvCourseNum = view.findViewById(R.id.tvCourseNum);
        tvOnLive = view.findViewById(R.id.tvOnLive);
        tvLive = view.findViewById(R.id.tvLive);
        tvOnLive.setOnClickListener(this);
        tvLive.setOnClickListener(this);
        childBeans = new Gson().fromJson(child, new TypeToken<List<ClassifyModel.DataBean.ChildBean>>() {
        }.getType());
        if (childBeans != null && childBeans.size() > 1) {
            cid = childBeans.get(0).getId();
            flowLayout.setVisibility(View.VISIBLE);
            flowLayout.setLayoutManager(new FlowLayoutManager() {
                @Override
                public boolean canScrollVertically() {
                    return false;
                }
            });
            setClassify(0);
            final ClassifyFlowAdapter flowAdapter = new ClassifyFlowAdapter(childBeans);
            flowAdapter.setOnItemChildClickListener(new BaseQuickAdapter.OnItemChildClickListener() {
                @Override
                public void onItemChildClick(BaseQuickAdapter adapter, View view, int position) {
                    setClassify(position);
                    flowAdapter.notifyDataSetChanged();
                    cid = childBeans.get(position).getId();
                    smartLayout.autoRefresh();
                }
            });
            flowLayout.setAdapter(flowAdapter);
        } else {
            cid = id;
            flowLayout.setVisibility(View.GONE);
        }
        setView();
    }

    private void setView() {
        data = new ArrayList<>();
        smartLayout.setEnableAutoLoadMore(true);//开启自动加载功能（非必须）
        smartLayout.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(final RefreshLayout refreshLayout) {
                refreshLayout.getLayout().postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        page = 1;
                        getData();
                    }
                }, 1000);
            }
        });
        smartLayout.setOnLoadMoreListener(new OnLoadMoreListener() {
            @Override
            public void onLoadMore(@NonNull final RefreshLayout refreshLayout) {
                refreshLayout.getLayout().postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        page++;
                        getData();
                    }
                }, 1000);
            }
        });
    }

    private void setClassify(int choose) {
        for (int i = 0; i < childBeans.size(); i++) {
            if (i == choose) {
                childBeans.get(i).setCheck(true);
            } else {
                childBeans.get(i).setCheck(false);
            }
        }
    }

    @Override
    protected void onFragmentVisibleChange(boolean isVisible) {
        if (isVisible) {
            smartLayout.autoRefresh();
        }
    }

    @Override
    protected void onFragmentFirstVisible() {

    }

    private void getData() {
        Map<String, String> map = new HashMap();
        map.put("cid", String.valueOf(cid));
        map.put("keyword", keyword);//关键字查询时使用
        map.put("priceOrder", "");//价格排序 desc asc 两种
        map.put("page", String.valueOf(page));//分页
        map.put("limit", String.valueOf(Constants.LIMIT));//分页
        map.put("type", String.valueOf(type));//课程种类 0视频录播 1视频直播 2语音 3文章 -1全部
        map.put("pay_type", "");//付费类型 0免费 1付费
        new HttpRequest(context).doGet(UrlConstants.course_list, null, map, CourseListModle.class, new HttpStringCallBack() {
            @Override
            public void onSuccess(Object result) {
                if (result instanceof CourseListModle) {
                    CourseListModle model = (CourseListModle) result;
                    if (page == 1) {
                        data.clear();
                        count = model.getData().getCount();
                        tvCourseNum.setText("共" + String.valueOf(count) + "个内容");
                        if (model.getData().getList().size() > 0) {
//                            no_data.setVisibility(View.GONE);
                            data = model.getData().getList();
                            adapter = new ClassifyAdapter(model.getData().getList());
                            rcvCourse.setAdapter(adapter);
                            if (adapter.getItemCount() < count) {
                                //还有多的数据
                                smartLayout.finishRefresh();
                            } else {
                                //没有更多数据（上拉加载功能将显示没有更多数据）
                                smartLayout.finishRefreshWithNoMoreData();
                            }
                        } else {
                            smartLayout.finishRefreshWithNoMoreData();
//                            no_data.setVisibility(View.VISIBLE);
                        }
                    } else {
                        data.addAll(model.getData().getList());
                        adapter.notifyDataSetChanged();
                        if (adapter.getItemCount() < count) {
                            //还有多的数据
                            smartLayout.finishLoadMore();
                        } else {
                            //没有更多数据（上拉加载功能将显示没有更多数据）
                            smartLayout.finishLoadMoreWithNoMoreData();//将不会再次触发加载更多事件
                        }
                    }
                }
            }

            @Override
            public void onFailure(int code, String msg) {

            }
        });
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.tvOnLive:
                break;
            case R.id.tvLive:
                break;
        }
    }
}
